#!/usr/bin/env python
#
# INTERFACE
#
# A graphical user interface based on GTK+
#
# This will be the primary means of making the search engine work. A few fields
# and buttons, and all that functionality will be within reach.
#
# I'm choosing PyGTK because I intend the search engine to be applied only to
# UNIX systems, for which GTK+ seems to be almost an ubiquitous choice anyway.
#
# VERSIONING
# - v1.0: able to search either by filename or by file content, doesn't freeze
#   screen during searches, able to update the database, but does freeze up in
#   the process. Displays results as file locations.
#

import os
import sys
import gtk
import query

class MainWindow:
    '''
    This may sound like a kindergarten all over again, but hey, everyone 
    forgets something every now and them, right?
    '''
    def search(self, widget, event, token=None):
        '''
        Searches the database via the module query.py using the specified
        input from the text field.
        '''
        self.query = self.queryfield.get_text()
        if self.query == "":
            self.statusbar.set_text("Empty query received.")
            return
        self.statusbar.set_text("Searching...")
        while not self.done:
            if self.indexsearch:
                self.results = query.index_search(self.query)
            else:
                self.results = query.simple_search(self.query)
            if self.results:
                self.done = True
            while gtk.events_pending():
                gtk.main_iteration()
        
        self.done = False

        self.total = 0
        for result in self.results:
            self.clipboard += result[0] + '\n'
            self.total += 1
            while gtk.events_pending():
                gtk.main_iteration()

        print "We found %d files containing '%s'" % (self.total, self.query)
        self.results_list.set_text("We found %d files containing '%s'" % (self.total, self.query))
        self.results_list.set_text(self.clipboard)
        self.clipboard = ""

        # spam protection:
        self.queryfield.set_text("")
        self.statusbar.set_text("%d files found." % self.total)
    
    def refresh(self, widget, event, data = None):
        self.statusbar.set_text("Refreshing the database...")
        while not self.done:
            while gtk.events_pending():
                gtk.main_iteration()
            self.refreshed = query.refresh()
            if self.refreshed:
                self.done = True
        self.done = False
        self.statusbar.set_text("Database refreshed.")

    def set_index(self, widget, data = None):
        if widget.get_active():
            print "Index searching is ON"
            self.indexsearch = True
        else:
            print "Index searching is OFF"
            self.indexsearch = False

    def __init__(self):
        # These variables are not part of the interface:
        self.results = None
        self.refreshed = False
        self.done = False
        self.clipboard = ""
        self.indexsearch = False

        # These and below are part of the user interface:
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("Search Engine")
        self.window.set_border_width(10)
        self.window.set_default_size(600, 500)
        self.window.connect("destroy", gtk.main_quit)

        # create widgets:
        self.maingrid = gtk.VBox(False, 0)
        self.horgrid = gtk.HBox(True, 0)
        self.searchgrid = gtk.HBox(False, 2)
        self.optionsgrid = gtk.HBox(False, 2)
        self.title = gtk.Label("Enter the terms you would like to search and click 'Search'")
        self.submitbutton = gtk.Button("Search")
        self.submitbutton.connect("clicked", self.search, None)
        self.queryfield = gtk.Entry(max=0)
        self.refreshbutton = gtk.Button("Refresh database")
        self.refreshbutton.connect("clicked", self.refresh, None)
        self.toggleindex = gtk.CheckButton("Search within files")
        self.toggleindex.connect("toggled", self.set_index)
        self.statusbar = gtk.Label("Ready")
        self.results_placeholder = gtk.VBox(False, 0)
        self.results_scroll = gtk.ScrolledWindow()
        self.results_scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
        self.results_list = gtk.Label("Your search results will appear here.")

        # pack widgets:
        self.searchgrid.pack_start(self.queryfield, True, True, 0)
        self.searchgrid.pack_start(self.submitbutton, False, False, 0)
        self.optionsgrid.pack_start(self.toggleindex, True, True, 0)
        self.optionsgrid.pack_start(self.refreshbutton, False, False, 0)
        self.maingrid.pack_start(self.title, False, False, 0)
        self.maingrid.pack_start(self.searchgrid, False, False, 0)
        self.maingrid.pack_start(self.optionsgrid, False, False, 0)
        self.maingrid.pack_start(self.statusbar, False, False, 0)
        self.results_scroll.add_with_viewport(self.results_list)
        self.results_placeholder.pack_start(self.results_scroll, True, True, 0)
        self.horgrid.pack_start(self.maingrid, True, False, 5)
        self.horgrid.pack_start(self.results_placeholder, True, True, 0)

        # show everything:
        self.submitbutton.show()
        self.title.show()
        self.queryfield.show()
        self.submitbutton.show()
        self.statusbar.show()
        self.refreshbutton.show()
        self.toggleindex.show()
        self.maingrid.show()
        self.horgrid.show()
        self.results_placeholder.show()
        self.results_list.show()
        self.results_scroll.show()
        self.searchgrid.show()
        self.optionsgrid.show()
        self.window.add(self.horgrid) # without this, they never exist!
        self.window.show()

    def main(self):
        gtk.main()

if __name__ == "__main__":
    base = MainWindow()
    base.main()
